package mp

import (
	"context"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeptSelectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptSelectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptSelectLogic {
	return &DeptSelectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeptSelectLogic) DeptSelect() (resp []*types.TreeList, err error) {
	resp = []*types.TreeList{
		{
			Value:    0,
			Label:    "顶级部门",
			Children: l.fetchChildren(0),
		},
	}
	return resp, nil
}

func (l *DeptSelectLogic) fetchChildren(pid int64) []*types.TreeList {
	var datas []*models.Dept
	db.FindDatasAsc(&datas, xb.Eq{"pid": pid})
	result := []*types.TreeList{}
	for _, v := range datas {
		tmp := &types.TreeList{
			Value:    v.Id,
			Label:    v.Title,
			Children: l.fetchChildren(int64(v.Id)),
		}
		result = append(result, tmp)
	}

	return result
}
